package cn.ligoo.part.web.springmvc.platform;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import cn.ligoo.part.domain.UserInfo;
import cn.ligoo.part.service.impl.FacadeImpl;
import cn.ligoo.part.web.Constants;

@Controller
@RequestMapping("/platform/password")
public class PasswordController {

	private final Logger logger = LoggerFactory.getLogger(PasswordController.class);

	@Resource
	private MessageSource message;

	@Resource
	private FacadeImpl facade;

	@RequestMapping(value = "/save", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request, @RequestParam String pwd_old, @RequestParam String pwd_cfm,
			@RequestParam String pwd_new) {
		logger.debug("...passworde.edit");

		// 空验证
		if (StringUtils.isBlank(pwd_old) || StringUtils.isBlank(pwd_cfm) || StringUtils.isBlank(pwd_new)) {
			String msg = message.getMessage("password.isBlank", null, null);
			return String.format(Constants.JSON_ERROR, msg);
		}

		// 确认密码验证
		if (!pwd_new.equals(pwd_cfm)) {
			String msg = message.getMessage("password.confirm.invalid", null, null);
			return String.format(Constants.JSON_ERROR, msg);
		}

		// 数据库验证
		UserInfo userInfo = (UserInfo) WebUtils.getSessionAttribute(request, Constants.SESSION_USER_INFO);
		if (!pwd_old.equals(userInfo.getPassword())) {
			String msg = message.getMessage("password.old.invalid", null, null);
			return String.format(Constants.JSON_ERROR, msg);
		}

		// 更新密码
		UserInfo t = new UserInfo();
		t.setId(userInfo.getId());
		t.setPassword(pwd_new);
		if (facade.getUserInfoService().modifyUserInfo(t) == 1) {
			userInfo.setPassword(pwd_new); // 更新当前Session中的密码
			String msg = message.getMessage("password.update.success", null, null);
			return String.format(Constants.JSON_SUCCESS, msg, null);
		}
		String msg = message.getMessage("errors.unknow", null, null);
		return String.format(Constants.JSON_ERROR, msg);
	}
}
